package com.cloud.bc.config;

import com.cloud.wx.config.WeiXinPayConfig;
import com.cloud.wx.pay.IWXPayDomain;
import com.cloud.wx.pay.WXPayConfig;
import com.cloud.wx.pay.WXPayConstants;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class WXPayConfigImpl extends WXPayConfig {
    private WeiXinPayConfig weiXinPayConfig;
    private byte[] certData;

    public WXPayConfigImpl(WeiXinPayConfig wxPayConfig) throws Exception {
        try {
            this.weiXinPayConfig = wxPayConfig;
            File file = new File(weiXinPayConfig.getCertPath());
            InputStream certStream = new FileInputStream(file);
            this.certData = new byte[(int) file.length()];
            certStream.read(this.certData);
            certStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String getAppID() {
        return weiXinPayConfig.getAppid();
    }

    public String getMchID() {
        return weiXinPayConfig.getMchid();
    }

    public String getKey() {
        return weiXinPayConfig.getKey();
    }

    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    @Override
    protected IWXPayDomain getWXPayDomain() {
        // 这个方法需要这样实现, 否则无法正常初始化WXPay
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {
            public void report(String domain, long elapsedTimeMillis, Exception ex) {
            }

            public DomainInfo getDomain(WXPayConfig config) {
                return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }

}

